package com.sts.sink.model;

import cn.hutool.core.lang.Pair;
import com.sts.common.utils.DbPairUtil;
import com.sts.jdbc.JdbcOperation;
import com.sts.jdbc.model.JdbcConnectionInfo;
import com.sts.sink.StsSink;
import com.sts.sink.impl.JdbcSinkImpl;
import com.sts.source.StsSource;
import com.sts.task.StsTask;
import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.InvocationTargetException;

@Getter
@Setter
public class JdbcSinkConfig extends BaseSinkConfig {

    private JdbcConnectionInfo jdbcConnectionInfo;
    private String schema;
    private String table;

    public JdbcSinkConfig() {
    }

    public JdbcSinkConfig(JdbcConnectionInfo jdbcConnectionInfo, String schema, String table) {
        this.jdbcConnectionInfo = jdbcConnectionInfo;
        this.schema = schema;
        this.table = table;
    }

    @Override
    public StsSink buildImpl(StsSource stsSource, StsTask stsTask) {
        Pair<Class<? extends JdbcSinkImpl>, Class<? extends JdbcOperation>> pair = DbPairUtil.getPair(jdbcConnectionInfo.getDbType());

        if (pair == null) {
            throw new RuntimeException("未找到对应jdbc的实现类和操作类");
        }

        Class<? extends JdbcSinkImpl> sinkClass = pair.getKey();
        Class<? extends JdbcOperation> operationClass = pair.getValue();

        try {
            JdbcOperation jdbcOperation = operationClass.getDeclaredConstructor().newInstance();
            return sinkClass.getConstructor(StsSource.class, JdbcSinkConfig.class, StsTask.class, JdbcOperation.class)
                    .newInstance(stsSource, this, stsTask, jdbcOperation);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
